package com.xbongbong.paas.help.menu;

import com.alibaba.fastjson.JSON;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.CoverPaasMenuEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.MenuTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.help.CloudCodeHelp;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.help.permission.PermissionHelp;
import com.xbongbong.paas.model.CoverPaasMenuModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.model.SearchCustomerCompanyModel;
import com.xbongbong.paas.model.SearchCustomerUserModel;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.service.PaasMenuService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.constant.PackageConstant;
import com.xbongbong.pro.domain.entity.SearchCustomerCompanyEntity;
import com.xbongbong.pro.domain.entity.SearchCustomerUserEntity;
import com.xbongbong.pro.enums.AccessLinkEnum;
import com.xbongbong.pro.enums.ContractCompareFeeStatusEnum;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.SoukeMealEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.CRMMenuEnum;
import com.xbongbong.pro.enums.menu.enums.NoHasQuickMenuEnum;
import com.xbongbong.pro.enums.permission.enums.AddProPermissionAliasEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.menu.pojo.MenuConfigPojo;
import com.xbongbong.pro.menu.pojo.MenuReturnPojo;
import com.xbongbong.pro.menu.pojo.dto.MenuNewListDTO;
import com.xbongbong.pro.menu.pojo.vo.AppMenuListVO;
import com.xbongbong.pro.menu.pojo.vo.MenuNewListVO;
import com.xbongbong.pro.menu.pojo.vo.PaasAppMenuVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.ContractCompareUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 首页的菜单列表
 * @author 吴峰
 * @version v1.0
 * @date 2019/7/8 19:38
 * @since v1.0
 */
@Component
public class ProMenuHelp {

    private static final Logger LOG = LoggerFactory.getLogger(ProMenuHelp.class);

    @Resource
    private PaasMenuService paasMenuService;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private SearchCustomerUserModel searchCustomerUserModel;
    @Resource
    private SearchCustomerCompanyModel searchCustomerCompanyModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private CloudCodeHelp cloudCodeHelp;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasAppService paasAppService;
    @Resource
    private CoverPaasMenuModel coverPaasMenuModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private ContractCompareUtil contractCompareUtil;

    /**
     * 获取菜单列表
     * @param menuNewListDTO 前端所传对象
     * @param menuNewListVO 返回容器
     * @param commonFormList 常用表单容器
     * @param productMenuList 产品菜单
     * @param menuConfigPojo 是否需要搜索个人配置项，公司配置，以及是否需要开启权限校验
     * @param featureList
     * @param num 自定义表单未使用的数量
     * @return 返回以appId为key的集合容器
     * @throws XbbException
     */
    public Map<Long, List<AppMenuListVO>> getMenuList(MenuNewListDTO menuNewListDTO, MenuNewListVO menuNewListVO,
                                                       List<AppMenuListVO> commonFormList, List<AppMenuListVO> productMenuList,
                                                       MenuConfigPojo menuConfigPojo, List<String> featureList, Integer num) throws XbbException{
        Map<Long, List<AppMenuListVO>> menuListMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        try {
            String corpid = menuNewListDTO.getCorpid();
            UserVO userVO = menuNewListDTO.getLoginUser();
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(userVO, userEntity);
            //根据套餐获取当前公司套餐不能看到的菜单
            List<String> unSeeMenuList = packageHelp.getUnSeeMenuList(menuNewListDTO.getCorpid());
            //进销存待系列菜单-根据套餐获取当前公司套餐不能看到的菜单
            List<String> jxcUnSeeMenuList = packageHelp.getJxcUnSeeMenuList(menuNewListDTO.getCorpid());

            // 获取常用表单
            boolean searchSelfConfig = menuConfigPojo.getSearchSelfConfig();
            boolean searchCompanyConfig = menuConfigPojo.getSearchCompanyConfig();
            List<MenuReturnPojo> commonMenuList = paasMenuService.getCommonFormList(menuNewListDTO, menuNewListVO, searchSelfConfig, searchCompanyConfig);
            if (Objects.equals(menuNewListDTO.getPlatform(), PlatFormEnum.WEB.getValue())) {
                Integer status = contractCompareUtil.getContractCompareStatus(corpid);
                // 非试用版
                if (!Objects.equals(status, ContractCompareFeeStatusEnum.TRIAL.getType())) {
                    Integer compareStaff = contractCompareUtil.getContractCompareStaff(corpid, userVO.getUserId());
                    // 坐席未开启，不展示合同比对菜单
                    if (Objects.equals(compareStaff, BasicConstant.ZERO)) {
                        commonMenuList.removeIf(item -> Objects.equals(item.getName(), XbbRefTypeEnum.CONTRACT_COMPARE_RESULT.getName()));
                    }
                }
            }
            Map<Long, MenuReturnPojo> commonFormIdSet = new HashMap<>(commonMenuList.size());
            commonMenuList.forEach(item->{
                commonFormIdSet.put(item.getMenuId(), item);
            });
            List<MenuReturnPojo> quickNewFromList = paasMenuService.getQuickNewFormList(menuNewListDTO, menuNewListVO, searchSelfConfig, searchCompanyConfig);
            Map<Long, MenuReturnPojo> quickNewFormIdSet = new HashMap<>(quickNewFromList.size());
            quickNewFromList.forEach(item->{
                quickNewFormIdSet.put(item.getMenuId(), item);
            });
            List<AppMenuListVO> quickNewFormList = new ArrayList<>();
            Map<String, Object> param = BeanUtil.convertBean2Map(menuNewListDTO, true);
            param.put("orderByStr", "app_id, sort, id desc");
            param.put("del", DelEnum.NORMAL.getDel());
            // 经销商关闭后经销商相关表单隐藏
            Boolean distributorEnable = paasAppService.validateAppEnable(null, XbbRefTypeEnum.DISTRIBUTOR.getAlias(), SaasMarkEnum.SAAS.getCode(), menuNewListDTO.getCorpid());
            if (!distributorEnable) {
                param.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
            }
            List<PaasMenuEntity> menuList = paasMenuModel.list(param);
            if(menuList == null){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            List<AppMenuListVO> menuExtList = new ArrayList<>();
            Map<Long, List<AppMenuListVO>> menuMap = new HashMap<>(menuList.size());
            UserVO loginUser = menuNewListDTO.getLoginUser();
            Boolean isAdminOrBoss = loginUser.isAdminOrBoss();
            Set<String> permissionAlias = loginUser.getPermSet();
            if (permissionAlias == null) {
                permissionAlias = new HashSet<>();
            }
            Integer isHomeList = menuConfigPojo.getIsHomeList();
            List<String> customerWhiteList = Arrays.asList(
                    XbbRefTypeEnum.CUSTOMER.getAlias(),
                    XbbRefTypeEnum.CUSTOMER_FOCUS.getAlias(),
                    XbbRefTypeEnum.CUSTOMER_DEAL.getAlias(),
                    XbbRefTypeEnum.CUSTOMER_FOLLOW.getAlias());
            List<String> clueWhiteList = Arrays.asList(
                    XbbRefTypeEnum.ALL_CLUE.getAlias());
            List<String> opportunityWhiteList = Arrays.asList(
                    XbbRefTypeEnum.SALES_OPPORTUNITY.getAlias(),
                    XbbRefTypeEnum.ALL_OPPORTUNITY.getAlias(),
                    XbbRefTypeEnum.KEY_OPPORTUNITY.getAlias());
            List<String> purchaseSubList = Arrays.asList(
                    XbbRefTypeEnum.SUPPLIER_CONTACT.getAlias(),
                    XbbRefTypeEnum.SUPPLIER.getAlias(),
                    XbbRefTypeEnum.PURCHASE.getAlias(),
                    XbbRefTypeEnum.RETURNED_PURCHASE.getAlias(),
                    XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getAlias(),
                    XbbRefTypeEnum.SMART_REPLENISHMENT.getAlias()
            );
            List<String> inventorySubList = Arrays.asList(
                    XbbRefTypeEnum.STOCK_SEARCH.getAlias(),
                    XbbRefTypeEnum.TRANSFER.getAlias(),
                    XbbRefTypeEnum.INVENTORY.getAlias(),
                    XbbRefTypeEnum.STOCK_FLOW_BILL.getAlias(),
                    XbbRefTypeEnum.BATCH_FLOW_BILL.getAlias(),
                    XbbRefTypeEnum.SEQ_SEARCH.getAlias(),
                    XbbRefTypeEnum.STOCK_STANDING_BOOK.getAlias(),
                    XbbRefTypeEnum.ASSEMBLE.getAlias(),
                    XbbRefTypeEnum.COST_ADJUST.getAlias()
            );
            List<String> productionSubList = Arrays.asList(
                    XbbRefTypeEnum.BOM_BILL.getAlias(),
                    XbbRefTypeEnum.PRODUCTION_ORDER.getAlias(),
                    XbbRefTypeEnum.SIMULATED_PRODUCTION.getAlias()
            );
            List<String> searchCustomerSubList = Arrays.asList(
                    XbbRefTypeEnum.EXCAVATE_CLUE.getAlias(),
                    XbbRefTypeEnum.COLLECTOR.getAlias(),
                    XbbRefTypeEnum.INDIVIDUAL_CLUE.getAlias(),
                    XbbRefTypeEnum.RECYCLE_BIN.getAlias()
            );
            List<String> instockSubList = Arrays.asList(
                    XbbRefTypeEnum.PURCHASE_INSTOCK.getAlias(),
                    XbbRefTypeEnum.REFUND_INSTOCK.getAlias(),
                    XbbRefTypeEnum.OTHER_INSTOCK.getAlias(),
                    XbbRefTypeEnum.PRODUCTION_INSTOCK.getAlias(),
                    XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getAlias()
            );
            List<String> outstockSubList = Arrays.asList(
                    XbbRefTypeEnum.CONTRACT_OUTSTOCK.getAlias(),
                    XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getAlias(),
                    XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getAlias(),
                    XbbRefTypeEnum.OTHER_OUTSTOCK.getAlias(),
                    XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getAlias()
            );
            List<String> fineSubList = Arrays.asList(
                    XbbRefTypeEnum.FINE_CLUE_QUERY_COMPANY.getAlias(),
                    XbbRefTypeEnum.FINE_CLUE_QUERY_CLUE.getAlias(),
                    XbbRefTypeEnum.FINE_CLUE_MAP_QUERY.getAlias(),
                    XbbRefTypeEnum.FINE_CLUE_BATCH_QUERY.getAlias()
            );
            List<String> dingGroupSubList = Arrays.asList(
                    XbbRefTypeEnum.SALE_BUNDLE.getAlias()
            );
            List<String> workOrderV2List = Arrays.asList(
                    XbbRefTypeEnum.WORK_ORDER_V2.getAlias(),
                    XbbRefTypeEnum.WORK_ORDER_V2_APPOINT.getAlias(),
                    XbbRefTypeEnum.WORK_ORDER_V2_POOL.getAlias(),
                    XbbRefTypeEnum.SLA_LOG.getAlias(),
                    XbbRefTypeEnum.RECEIPT_ORDER.getAlias(),
                    XbbRefTypeEnum.SERVICE_PROJECT.getAlias());
            // 增加 jxc 分组权限
            for (String purchaseAlias : purchaseSubList) {
                if (permissionAlias.contains(purchaseAlias)) {
                    permissionAlias.add(XbbRefTypeEnum.PURCHASE_MANAGEMENT.getAlias());
                    break;
                }
            }
            for (String inventoryAlias : inventorySubList) {
                if (permissionAlias.contains(inventoryAlias)) {
                    permissionAlias.add(XbbRefTypeEnum.INVENTORY_MANAGEMENT.getAlias());
                    break;
                }
            }
            for (String productionAlias : productionSubList) {
                if (permissionAlias.contains(productionAlias)) {
                    permissionAlias.add(XbbRefTypeEnum.PRODUCTION_MANAGEMENT.getAlias());
                    break;
                }
            }
            for (String instockAlias : instockSubList) {
                if (permissionAlias.contains(instockAlias)) {
                    permissionAlias.add(XbbRefTypeEnum.INSTOCK.getAlias());
                    break;
                }
            }
            for (String outstockAlias : outstockSubList) {
                if (permissionAlias.contains(outstockAlias)) {
                    permissionAlias.add(XbbRefTypeEnum.OUTSTOCK.getAlias());
                    break;
                }
            }
            // 判断是否是搜客坐席增加搜客权限, 试用搜客时公司所有员工都可试用
            SearchCustomerUserEntity searchCustomerUserEntity = searchCustomerUserModel.getByKey(loginUser.getUserId(), loginUser.getCorpid());
            // 判断搜客是否过期
            SearchCustomerCompanyEntity soukeEntity = searchCustomerCompanyModel.getByCorpid(loginUser.getCorpid(), SoukeMealEnum.SOUKE.getType());
            if (soukeEntity == null || soukeEntity.getExtraExpiry() <= DateUtil.getInt()){
                searchCustomerUserEntity = null;
            }
            // 增加搜客试用套餐
            if (soukeEntity != null && soukeEntity.getExtraExpiry() - soukeEntity.getAddTime() < 4 * RedisConstant.LONG_DURATION
                    && soukeEntity.getExtraExpiry() > DateUtil.getInt()) {
                if (searchCustomerUserEntity == null) {
                    searchCustomerUserEntity = new SearchCustomerUserEntity();
                }
                searchCustomerUserEntity.setStaff(1);
            }
            for (String searchCustomerAlias : searchCustomerSubList) {
                if (searchCustomerUserEntity != null && Objects.equals(searchCustomerUserEntity.getStaff(), 1)) {
                    permissionAlias.add(searchCustomerAlias);
                }
            }

            // 添加精线索的搜客首页的子菜单权限，父菜单已经校验过
            for (String fineString : fineSubList) {
                permissionAlias.add(fineString);
            }
            // 需要开启库存流水才需要有菜单

            Map<String, String> configValueMap = companyConfigModel.getConfigValueMap(menuNewListDTO.getCorpid(), Arrays.asList(CompanyConfigEnum.ENABLE_BATCH_SHELF_MANAGEMENT.getAlias(), CompanyConfigEnum.ENABLE_SEQ_MANAGEMENT.getAlias()));
            boolean needBatchFlow = BasicConstant.IS_USE.toString().equals(configValueMap.get(CompanyConfigEnum.ENABLE_BATCH_SHELF_MANAGEMENT.getAlias()));
            boolean needSeqSearch = BasicConstant.IS_USE.toString().equals(configValueMap.get(CompanyConfigEnum.ENABLE_SEQ_MANAGEMENT.getAlias()));
            String key = menuNewListDTO.getCorpid() + StringConstant.COLON + CompanyConfigEnum.WORK_ORDER_V2_POOL_SET.getAlias();
            boolean enablePoolSet = Objects.equals(BasicConstant.IS_USE.toString(), companyConfigModel.getByConfigAlias(CompanyConfigEnum.WORK_ORDER_V2_POOL_SET.getAlias(), RedisConstant.KEY_COMPANY_CONFIG, key, menuNewListDTO.getCorpid(), RedisTimeConstant.TEN_MINUTES, "0"));

            // 构建paasPermissionSet, 键为menuId
            Set<Long> paasPermissions = ProPermissionHelp.getPaasViewMenuIdSet(loginUser.getPaasPermissions());
            Set<String> dynamicPermSet = loginUser.getDynamicPermSet();
            Map<String, XbbRefTypeEnum> nameMap = new HashMap<>(XbbRefTypeEnum.values().length);
            for (XbbRefTypeEnum xbbRefTypeEnum: XbbRefTypeEnum.values()) {
                nameMap.put(xbbRefTypeEnum.getAlias(), xbbRefTypeEnum);
            }
            //TODO 处理排序
            //handleCoverMenuSort(menuNewListDTO.getCorpid(),menuList);
            for (PaasMenuEntity paasMenuEntity : menuList) {
                Integer saasMark = paasMenuEntity.getSaasMark();
                String alias = paasMenuEntity.getAlias();
                if (SaasMarkEnum.SAAS.getCode().equals(saasMark)) {
                    // saas 菜单
                    if (StringUtil.isEmpty(alias)) {
                        LOG.error("paasMenuEntity 中 alias为空, " + JSON.toJSONString(paasMenuEntity));
                        continue;
                    } else if (unSeeMenuList.contains(alias)|| jxcUnSeeMenuList.contains(alias)) {
                        continue;
                    }
                    // 手机上，列表上，不展示访客计划、客户对账单
//                    boolean showNoneFlag = Objects.equals(isHomeList, BasicConstant.ONE) && Objects.equals(PlatFormEnum.DINGTALK.getValue(), menuNewListDTO.getPlatform()) && (Objects.equals(XbbRefTypeEnum.COMMUNICATE_PLAN.getAlias(), alias));
//                    if (showNoneFlag) {
//                        continue;
//                    }
                    // 手机端不展示客户对账单的信息
                    if (Objects.equals(XbbRefTypeEnum.CUSTOMER_STATEMENT.getAlias(), alias) && Objects.equals(PlatFormEnum.DINGTALK.getValue(), menuNewListDTO.getPlatform())) {
                        continue;
                    }
                    // web 和 dingtalk 都不展示信用流水
                    if (Objects.equals(XbbRefTypeEnum.CREDIT_CARD_BILL.getAlias(), alias)) {
                        continue;
                    }
                    //手机端不展示支付流水的信息
                    if (Objects.equals(XbbRefTypeEnum.ONLINE_PAYMENT_FLOW.getAlias(), alias) && Objects.equals(PlatFormEnum.DINGTALK.getValue(), menuNewListDTO.getPlatform())) {
                        continue;
                    }
                    if (Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2_POOL.getAlias(), alias) && !enablePoolSet) {
                        // 工单池未启用，菜单列表不显示
                        continue;
                    }
                    /*
                     * 只用于构建菜单时的权限判断
                     */
                    String checkAlias;
                    if (customerWhiteList.contains(alias)) {
                        checkAlias = ProPermissionAliasEnum.CUSTOMER_VIEW.getAlias();
                    } else if (opportunityWhiteList.contains(alias)) {
                        checkAlias = ProPermissionAliasEnum.OPPORTUNITY_VIEW.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.PRODUCT.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.PRODUCT_VIEW.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.SEND_MESSAGE.getAlias())) {
                        // 短信群发
                        checkAlias = ProPermissionAliasEnum.SMS_SEND.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.RECORD_VIEW.getAlias())
                            || Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.REPLY_VIEW.getAlias())) {
                        // 短信查看或收件箱
                        checkAlias = ProPermissionAliasEnum.SMS_VIEW.getAlias();
                    } else if (clueWhiteList.contains(alias)) {
                        checkAlias = ProPermissionAliasEnum.CLUE_VIEW.getAlias();
                    } else if ( dingGroupSubList.contains(alias) ) {
                        checkAlias = ProPermissionAliasEnum.SALE_BUNALE_VIEW.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getAlias()) && Objects.equals(paasMenuEntity.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                        checkAlias = ProPermissionAliasEnum.DISTRIBUTOR_PROFILE.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.CONTACT.getAlias()) && Objects.equals(paasMenuEntity.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                        checkAlias = ProPermissionAliasEnum.DISTRIBUTOR_CONTACT.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getAlias()) && Objects.equals(paasMenuEntity.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                        checkAlias = ProPermissionAliasEnum.DISTRIBUTOR_COMMUNICATE.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.CONTRACT.getAlias()) && Objects.equals(paasMenuEntity.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                        checkAlias = ProPermissionAliasEnum.ORDER.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.REFUND.getAlias()) && Objects.equals(paasMenuEntity.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                        checkAlias = ProPermissionAliasEnum.RETURN.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.STATEMENTLIST.getAlias();
                    }else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.WAIT_PURCHASE.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.ORDER_ON_PIN.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.WAIT_OUTSTOCK.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.PENDING_OUTSTOCK.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.PENDING_INSTOCK.getAlias();
                    }  else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.COMPETITOR.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.COMPETITOR_VIEW.getAlias();
                    }  else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.REFUND.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.REFUND_VIEW.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.WORK_ORDER_V2_APPOINT.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.WORK_ORDER_V2_ASSIGNED.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.WORK_ORDER_V2_POOL.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.WORK_ORDER_V2_POOL_VIEW.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.RECEIPT_ORDER.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.RECEIPT_ORDER_VIEW.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.SERVICE_PROJECT.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.SERVICE_PROJECT_VIEW.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.SLA_LOG.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.SLA_LOG_VIEW.getAlias();
                    } else if (Objects.equals(paasMenuEntity.getAlias(), XbbRefTypeEnum.CONTRACT_COMPARE_RESULT.getAlias())) {
                        checkAlias = ProPermissionAliasEnum.CONTRACT_COMPARE_RESULT_VIEW.getAlias();
                    } else {
                        checkAlias = alias;
                    }
                    // 酷应用所有人都可见
                    if (!Objects.equals(checkAlias, XbbRefTypeEnum.COOL_APP.getAlias())){
                        // 无权限
                        if (!isAdminOrBoss && !permissionAlias.contains(checkAlias) && !Objects.equals(MenuTypeEnum.GROUP.getType(), paasMenuEntity.getType())) {
                            continue;
                        }
                    }
                    if (!needBatchFlow && Objects.equals(alias, XbbRefTypeEnum.BATCH_FLOW_BILL.getAlias())) {
                        continue;
                    }
                    if (!needSeqSearch && Objects.equals(alias, XbbRefTypeEnum.SEQ_SEARCH.getAlias())) {
                        continue;
                    }
                    // web端不需要查重菜单；手机端不需要跟进客户和客户回收站菜单
                    if (Objects.nonNull(isHomeList) && (Objects.equals(isHomeList, 1) || Objects.equals(isHomeList, 2))) {
                        boolean result = (Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_RECYCLE.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.CLUE_RECYCLE.getAlias()))
                                && Objects.equals(menuNewListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue());
                        if (result) {
                            continue;
                        } else if ((Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_DUPLICATE.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.CLUE_DUPLICATE.getAlias()))
                                && Objects.equals(menuNewListDTO.getPlatform(), PlatFormEnum.WEB.getValue())) {
                            continue;
                        }
                    }
                } else if (SaasMarkEnum.PAAS.getCode().equals(saasMark)) {
                    // 无权限的paas菜单
                    if (!isAdminOrBoss && !paasPermissions.contains(paasMenuEntity.getId()) && !dynamicPermSet.contains(paasMenuEntity.getAlias()) && !Objects.equals(MenuTypeEnum.GROUP.getType(), paasMenuEntity.getType())) {
                        continue;
                    }
                }

                AppMenuListVO appMenuListVO = new AppMenuListVO();
                BeanUtil.copyProperties(paasMenuEntity, appMenuListVO);
                String url = appMenuListVO.getUrl();
                String mobileUrl = appMenuListVO.getMobileUrl();
                // 不需要快捷新建的菜单
                NoHasQuickMenuEnum noHasQuickMenuEnum = NoHasQuickMenuEnum.getByAlias(paasMenuEntity.getAlias());
                Boolean noHasQuickNew = !noHasQuickMenuEnum.equals(NoHasQuickMenuEnum.NONE)
                        && (Objects.equals(menuNewListDTO.getPlatform(), noHasQuickMenuEnum.getPlatform())
                        || Objects.equals(PlatFormEnum.ALL.getValue(), noHasQuickMenuEnum.getPlatform()));
                // 快捷新建列表，不需要快捷新建的表单
                if (Objects.equals(isHomeList, 2) && noHasQuickNew) {
                    if (Objects.equals(PlatFormEnum.DINGTALK.getValue(), menuNewListDTO.getPlatform()) && Objects.equals(menuNewListDTO.getQuickDingtalk(), 1)) {
                        continue;
                    } else {
                        appMenuListVO.setHasQuickNewFlag(0);
                    }
                }

                XbbRefTypeEnum xbbRefTypeEnum = nameMap.get(paasMenuEntity.getAlias()) == null ? XbbRefTypeEnum.UNKNOWN : nameMap.get(paasMenuEntity.getAlias());
                appMenuListVO.setBusinessType(xbbRefTypeEnum.getCode());
                if (MenuTypeEnum.getFormList().contains(paasMenuEntity.getType()) && Objects.equals(SaasMarkEnum.SAAS.getCode(), paasMenuEntity.getSaasMark())) {
                    String sourceName = I18nMessageUtil.getMessage(xbbRefTypeEnum.getI18nName(), Locale.CHINA);
                    appMenuListVO.setSourceName(sourceName);
                } else {
                    appMenuListVO.setSourceName(paasMenuEntity.getName());
                }
                if (CRMMenuEnum.COMMUNICATE_PLAN.getAlias().equals(paasMenuEntity.getAlias())) {
                    mobileUrl = AccessLinkEnum.COMMUNICATE_PLAN.getMobileUrl();
                    appMenuListVO.setIsAdminCommunicatePlan(false);
                }
                Boolean adminSignIn = isAdminOrBoss || permissionAlias.contains(ProPermissionAliasEnum.SIGN_IN_STATISTIC.getAlias());
                // 签到、工作报告、访客计划
                if (adminSignIn && CRMMenuEnum.SIGN_IN.getAlias().equals(paasMenuEntity.getAlias())) {
                    url = AccessLinkEnum.ADMIN_SIGN_IN.getUrl();
                    mobileUrl = AccessLinkEnum.ADMIN_SIGN_IN.getMobileUrl();
                } else if (isAdminOrBoss && CRMMenuEnum.COMMUNICATE_PLAN.getAlias().equals(paasMenuEntity.getAlias())) {
                    url = AccessLinkEnum.ADMIN_COMMUNICATE_PLAN.getUrl();
                    mobileUrl = AccessLinkEnum.ADMIN_COMMUNICATE_PLAN.getMobileUrl();
                    appMenuListVO.setIsAdminCommunicatePlan(true);
                }
                if (Objects.nonNull(num) && num > 0 && Objects.equals(SaasMarkEnum.PAAS.getCode(), paasMenuEntity.getSaasMark())) {
                    // 没有自定义表单的
                    appMenuListVO.setPackageLimit(1);
                    appMenuListVO.setMessage(String.format(I18nMessageUtil.getMessage(PackageConstant.CUSTOM_FORM_SIZE_MESSAGE), num));
                }
                if (StringUtil.isNotEmpty(url)) {
                    StringBuilder stringBuilder = new StringBuilder(url)
                            .append("?subBusinessType=").append(xbbRefTypeEnum.getCode())
                            .append("&appId=").append(appMenuListVO.getAppId())
                            .append("&menuId=").append(appMenuListVO.getId())
                            .append("&saasMark=").append(appMenuListVO.getSaasMark())
                            .append("&distributorMark=").append(paasMenuEntity.getDistributorMark());
                    appMenuListVO.setUrl(stringBuilder.toString());
                }

                if (StringUtil.isNotEmpty(mobileUrl)) {
                    StringBuilder stringBuilder = new StringBuilder(mobileUrl)
                            .append("?subBusinessType=").append(xbbRefTypeEnum.getCode())
                            .append("&appId=").append(appMenuListVO.getAppId())
                            .append("&name=").append(appMenuListVO.getName())
                            .append("&saasMark=").append(appMenuListVO.getSaasMark())
                            .append("&distributorMark=").append(paasMenuEntity.getDistributorMark());
                    if (Objects.equals(XbbRefTypeEnum.STOCK_SEARCH.getAlias(), alias)) {
                        stringBuilder.append("&businessType="+XbbRefTypeEnum.PRODUCT.getCode());
                    }
                    if (Objects.equals(XbbRefTypeEnum.COMMUNICATE_PLAN.getAlias(), alias)) {
                        // 访客计划模块
                        stringBuilder.append("&businessType="+XbbRefTypeEnum.COMMUNICATE_PLAN.getCode());
                        PaasFormEntity paasFormEntity = paasFormModel.getByMenuIdAndBusinessType(paasMenuEntity.getId().intValue(), menuNewListDTO.getCorpid(), XbbRefTypeEnum.COMMUNICATE_PLAN.getCode());
                        if (null != paasFormEntity){
                            stringBuilder.append("&formId="+paasFormEntity.getId());
                        }
                    }
                    if (Objects.equals(alias, XbbRefTypeEnum.CUSTOMER.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_FOCUS.getAlias())
                            || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_DEAL.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_FOLLOW.getAlias())
                            || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_PUBLIC.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_RECYCLE.getAlias())
                            || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_NEARBY.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.ALL_OPPORTUNITY.getAlias())
                            || Objects.equals(alias, XbbRefTypeEnum.KEY_OPPORTUNITY.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.ALL_CLUE.getAlias())
                            || Objects.equals(alias, XbbRefTypeEnum.CLUE_PUBLIC.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.CLUE_RECYCLE.getAlias())) {
                        stringBuilder.append("&menuId=").append(appMenuListVO.getParentId());
                    }else if (Objects.equals(alias, XbbRefTypeEnum.PAYMENT_TASK.getAlias()) && PlatFormEnum.DINGTALK.getValue().equals(menuNewListDTO.getPlatform())){
                        PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PAYMENT_TASK.getCode(), menuNewListDTO.getCorpid());
                        if (Objects.nonNull(paasFormEntity)) {
                            stringBuilder.append("&formId=").append(paasFormEntity.getId())
                                    .append("&businessType=").append(XbbRefTypeEnum.PAYMENT_TASK.getCode())
                                    .append("&idAdminOrBoss=").append(userVO.isAdminOrBoss())
                                    .append("&menuId=").append(appMenuListVO.getId());
                        }
                    } else {
                        stringBuilder.append("&menuId=").append(appMenuListVO.getId());
                    }
//                    else if (Objects.equals(alias, XbbRefTypeEnum.COMMUNICATE_PLAN.getAlias()) && PlatFormEnum.DINGTALK.getValue().equals(menuNewListDTO.getPlatform())){
//                        PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.COMMUNICATE_PLAN.getCode(), menuNewListDTO.getCorpid());
//                        if (Objects.nonNull(paasFormEntity)) {
//                            stringBuilder.append("&formId=").append(paasFormEntity.getId())
//                                    .append("&businessType=").append(XbbRefTypeEnum.COMMUNICATE_PLAN.getCode())
//                                    .append("&idAdminOrBoss=").append(userVO.isAdminOrBoss())
//                                    .append("&menuId=").append(appMenuListVO.getId());
//                        }
//                    }
                    appMenuListVO.setMobileUrl(stringBuilder.toString());
                }
                // 常用表单
                if (!commonFormIdSet.isEmpty() && commonFormIdSet.containsKey(paasMenuEntity.getId())) {
                    appMenuListVO.setCommonFormFlag(1);
                    MenuReturnPojo menuReturnPojo = commonFormIdSet.get(paasMenuEntity.getId());
                    appMenuListVO.setSort(menuReturnPojo.getSort());
                    commonFormList.add(appMenuListVO);
                }
                // 快捷新建
                Boolean hasPermission = validateAddPermission(menuNewListDTO.getLoginUser(), paasMenuEntity);
                if (!hasPermission) {
                    appMenuListVO.setHasQuickNewFlag(0);
                }
                if (!quickNewFormIdSet.isEmpty() && quickNewFormIdSet.containsKey(paasMenuEntity.getId()) && hasPermission) {
                    appMenuListVO.setQuickNewFormFlag(1);
                    AppMenuListVO quick = new AppMenuListVO();
                    BeanUtil.copyProperties(appMenuListVO, quick);
                    MenuReturnPojo menuReturnPojo = quickNewFormIdSet.get(paasMenuEntity.getId());
                    quick.setSort(menuReturnPojo.getSort());
                    quickNewFormList.add(quick);
                }
                if (paasMenuEntity.getParentId() == 0) {
                    // 存放一级菜单
                    menuExtList.add(appMenuListVO);
                } else {
                    // 获取二级菜单，并放到容器中
                    if (Objects.isNull(menuMap.get(paasMenuEntity.getParentId()))) {
                        List<AppMenuListVO> paasMenuList = new ArrayList<>();
                        paasMenuList.add(appMenuListVO);
                        menuMap.put(paasMenuEntity.getParentId(), paasMenuList);
                    } else {
                        List<AppMenuListVO> paasMenuList = menuMap.get(paasMenuEntity.getParentId());
                        paasMenuList.add(appMenuListVO);
                        menuMap.put(paasMenuEntity.getParentId(), paasMenuList);
                    }
                }
            }
            // 存放快捷新建表单

            menuNewListVO.setQuickNewList(sort(quickNewFormList));
            // 将子菜单放入父菜单
            List<AppMenuListVO> paasMenuEntityList = new ArrayList<>();
            menuExtList.forEach((item)->{
                AppMenuListVO appMenuListVO = new AppMenuListVO();
                BeanUtil.copyProperties(item, appMenuListVO);
                if(Objects.nonNull(menuMap.get(item.getId())) && !menuMap.get(item.getId()).isEmpty()
                        && MenuTypeEnum.GROUP.getType().equals(item.getType()) && Objects.equals(isHomeList, 1)){
                    // 首页菜单列表
                    appMenuListVO.setSubMenuList(menuMap.get(item.getId()));
                    paasMenuEntityList.add(appMenuListVO);
                } else if (!MenuTypeEnum.GROUP.getType().equals(item.getType())){
                    // 非分组的一级菜单（表单、流程表单、菜单）
                    paasMenuEntityList.add(appMenuListVO);
                } else if (MenuTypeEnum.GROUP.getType().equals(item.getType()) && Objects.equals(isHomeList, 2)) {
                    // 首页菜单设置，管理中心菜单设置
                    List<AppMenuListVO> appMenuList = menuMap.get(item.getId());
                    appMenuListVO.setSubMenuList(appMenuList == null ? new ArrayList<>() : appMenuList);
                    paasMenuEntityList.add(appMenuListVO);
                }
            });

            cloudCodeHelp.setMenuActions(menuNewListDTO.getCorpid(), menuNewListDTO.getPlatform(), paasMenuEntityList);

            // 将菜单列表分应用存放到容器中
            for (AppMenuListVO item : paasMenuEntityList) {
                if (Objects.isNull(menuListMap.get(item.getAppId()))) {
                    List<AppMenuListVO> paasMenuList = new ArrayList<>();
                    paasMenuList.add(item);
                    menuListMap.put(item.getAppId(), paasMenuList);
                } else {
                    List<AppMenuListVO> paasMenuList = menuListMap.get(item.getAppId());
                    paasMenuList.add(item);
                    menuListMap.put(item.getAppId(), paasMenuList);
                }
            }
            //跨应用拖拽菜单的排序还原
            if(commonHelp.isOpenMenuWhite(corpid)){
                handleCoverMenuSort(menuList,menuListMap);
            }
        }catch (Exception e) {
            LOG.error("menuService.getMenuList获取菜单列表出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuListMap;
    }


    /**
     * @description 处理跨应用移动一级菜单的排序
     * @author yanglei
     * @date 2022/11/30 13:42
     * @param paasMenuEntityList 所有菜单list
     * @param menuListMap
     */
    public void handleCoverMenuSort(List<PaasMenuEntity> paasMenuEntityList,Map<Long, List<AppMenuListVO>> menuListMap){
        //将一级菜单的排序还原成保存时的样子
        for (PaasMenuEntity paasMenuEntity : paasMenuEntityList) {
            outer: for(Map.Entry<Long,List<AppMenuListVO>> entry : menuListMap.entrySet()){
                for (AppMenuListVO appMenuListVO : entry.getValue()) {
                    if (Objects.equals(appMenuListVO.getId(),paasMenuEntity.getId())){
                        appMenuListVO.setSort(paasMenuEntity.getSort());
                        break outer;
                    }
                }
            }
        }
    }

    /**
     * @description 跨应用移动菜单处理
     * @author yanglei
     * @date 2022/11/30 9:13
     * @param appVOList
     * @param corpid
     */
    public void formatAppMenuVoList(List<PaasAppMenuVO> appVOList, String corpid){
        //跨应用移动过的菜单
        List<CoverPaasMenuEntity> coverPaasMenuList = coverPaasMenuModel.getList(corpid);
        if (CollectionsUtil.isEmpty(coverPaasMenuList)){
            return;
        }
        //每个应用对应的菜单列表
        Map<Long, List<AppMenuListVO>> appSubMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //菜单id -> 菜单Map;
        Map<Long, AppMenuListVO> allMenuVOMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasAppMenuVO paasAppMenuVO : appVOList) {
            //应用之外的一级菜单
            List<AppMenuListVO> topMenuList = paasAppMenuVO.getSubMenuList();
            if (CollectionsUtil.isEmpty(topMenuList)){
                continue;
            }
            appSubMap.put(paasAppMenuVO.getId(),topMenuList);
            Map<Long, AppMenuListVO> subMenuMap = topMenuList.stream().collect(Collectors.toMap(AppMenuListVO::getId, AppMenuListVO -> AppMenuListVO));
            allMenuVOMap.putAll(subMenuMap);
        }
        for (CoverPaasMenuEntity coverPaasMenuEntity : coverPaasMenuList) {
            Long menuId = coverPaasMenuEntity.getMenuId();
            //移动之后的应用id
            Long linkAppId = coverPaasMenuEntity.getLinkAppId();
            List<AppMenuListVO> newMenuList = appSubMap.get(coverPaasMenuEntity.getLinkAppId());
            if (Objects.isNull(newMenuList)){
                newMenuList = new ArrayList<>();
            }
            AppMenuListVO appMenuListVO = allMenuVOMap.get(coverPaasMenuEntity.getMenuId());
            if (Objects.nonNull(appMenuListVO)){
                //每个菜单实际的appId
                Long appId = appMenuListVO.getAppId();
                List<AppMenuListVO> beforeMenuList = appSubMap.get(appId);
                if (!Objects.equals(appId,linkAppId)){
                    newMenuList.add(appMenuListVO);
                    beforeMenuList.removeIf(item -> Objects.equals(item.getId(),menuId));
                    //塞入老的
                    appSubMap.put(appId,beforeMenuList);
                    //塞入新的
                    appSubMap.put(linkAppId,newMenuList);
                }
            }
        }
        //最后在排一下序
        for (PaasAppMenuVO paasAppMenuVO : appVOList) {
            if (Objects.nonNull(appSubMap.get(paasAppMenuVO.getId()))){
                List<AppMenuListVO> secondMenuList = appSubMap.get(paasAppMenuVO.getId());
                sort(secondMenuList);
                //List<AppMenuListVO> sortList = appSubMap.get(paasAppMenuVO.getId()).stream().sorted(Comparator.comparingInt(AppMenuListVO::getSort)).collect(Collectors.toList());
                paasAppMenuVO.setSubMenuList(secondMenuList);
            }
        }
    }
    /**
     * 校验是否有新建权限
     * @param userVO
     * @param item
     * @return true:有新建权限 false：无新建权限
     */
    public boolean validateAddPermission(UserVO userVO, PaasMenuEntity item) {
        if (userVO.isAdminOrBoss()) {
            return true;
        }
        if (Objects.equals(MenuTypeEnum.GROUP.getType(), item.getType())
                || Objects.equals(MenuTypeEnum.MENU.getType(), item.getType())) {
            return true;
        }
        if (Objects.equals(item.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByAlias(item.getAlias());
            CRMMenuEnum crmMenuEnum = CRMMenuEnum.getByCode(xbbRefTypeEnum.getCode());
            Integer businessType = xbbRefTypeEnum.getCode();
            if (Objects.nonNull(crmMenuEnum) && StringUtil.isNotEmpty(crmMenuEnum.getParent())) {
                businessType = XbbRefTypeEnum.getByAlias(crmMenuEnum.getParent()).getCode();
            }
            // 签到和库存查询、模拟生产是没有新建操作的，所以不需要判断权限
            if (Objects.equals(XbbRefTypeEnum.SIGNIN.getCode(), businessType)
                    || Objects.equals(XbbRefTypeEnum.STOCK_SEARCH.getCode(), businessType)
                    || Objects.equals(XbbRefTypeEnum.SIMULATED_PRODUCTION.getCode(), businessType)

            ) {
                return true;
            }
            AddProPermissionAliasEnum addProPermissionAliasEnum = AddProPermissionAliasEnum.getByCode(businessType);
            if(Objects.isNull(addProPermissionAliasEnum)) {
                return false;
            }
            if (!userVO.isAdminOrBoss() && !userVO.getPermSet().contains(addProPermissionAliasEnum.getAlias())) {
                return false;
            }
            //预收款的新建依赖于回款单的新建
            if(Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(),addProPermissionAliasEnum.getCode())){
                addProPermissionAliasEnum = AddProPermissionAliasEnum.getByCode(XbbRefTypeEnum.PAYMENT_SHEET.getCode());
                if(Objects.isNull(addProPermissionAliasEnum)) {
                    return false;
                }
                if (!userVO.isAdminOrBoss() && !userVO.getPermSet().contains(addProPermissionAliasEnum.getAlias())) {
                    return false;
                }
            }
        } else {
            Set<Long> idSet = ProPermissionHelp.getPaasCreateMenuIdSet(userVO.getPaasPermissions());
            if (!userVO.isAdminOrBoss() && !idSet.contains(item.getId())) {
                return false;
            }
        }
        return true;
    }

    /**
     * 校验是否有查看权限
     * @param userVO
     * @param alias
     * @param menuId
     * @param saasMark
     * @return true:有权限 false：无权限
     */
    public boolean validateViewPermission(UserVO userVO, String alias, Integer saasMark, Long menuId) {
        if (userVO.isAdminOrBoss()) {
            return true;
        }
        if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
            String hasViewPermission = PermissionHelp.hasViewPermission(alias);
            if (!userVO.isAdminOrBoss() && !userVO.getPermSet().contains(hasViewPermission)) {
                return false;
            }
        } else {
            Set<Long> idSet = ProPermissionHelp.getPaasViewMenuIdSet(userVO.getPaasPermissions());
            if (!userVO.isAdminOrBoss() && !idSet.contains(menuId)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 为快捷新建和常用表单排序
     * @param appMenuList
     * @return
     */
    public List<AppMenuListVO> sort(List<AppMenuListVO> appMenuList) {
        if (!appMenuList.isEmpty()) {
            Collections.sort(appMenuList, new Comparator<AppMenuListVO>() {
                @Override
                public int compare(AppMenuListVO o1, AppMenuListVO o2) {
                    //升序,sort因为某种原因可能为null, 这边把他们放最后
                    int o1Int = o1.getSort() != null ? o1.getSort() : 999;
                    int o2Int = o2.getSort() != null ? o2.getSort() : 999;
                    return o1Int - o2Int;
                }
            });
        }
        return appMenuList;
    }

}
